import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class DeepSeekService {
  static const String _apiKey = 'sk-51b339956d4c40e9b290e15e22190d7b'; // 替换为你的API Key
  static const String _baseUrl = 'https://api.deepseek.com/v1';

  final Dio _dio = Dio();

  // ✅ 修复SSE解析 + 字符编码
  Future<void> streamChatResponse({
    required String message,
    required Function(String) onData,
  }) async {
    try {
      final response = await _dio.post(
        '$_baseUrl/chat/completions',
        options: Options(
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer $_apiKey',
          },
          responseType: ResponseType.stream,
        ),
        data: {
          'model': 'deepseek-chat',
          'messages': [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": message},
          ],
          'stream': true,
        },
      );

      final responseStream = response.data as ResponseBody;
      final utf8Decoder = utf8.decoder;

      await for (final chunk in responseStream.stream) {
        final chunkStr = await utf8Decoder.convert(chunk);
        final lines = chunkStr.split('\n');

        for (final line in lines) {
          if (line.startsWith('data:') && line != 'data: [DONE]') {
            final jsonStr = line.substring(5).trim();
            try {
              final jsonData = jsonDecode(jsonStr);
              final content = jsonData['choices'][0]['delta']['content'] ?? '';
              if (content.isNotEmpty) {
                onData(content); // 传递正确解码的文本
              }
            } catch (e) {
              debugPrint('JSON解析跳过: $e | 原始数据: $jsonStr');
            }
          }
        }
      }
    } catch (e) {
      debugPrint('流式请求错误: $e');
      rethrow;
    }
  }
}